package userhandler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/userprofitlog"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
)

func HandleGetPlaceUserList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	param.UserLoginIsAdmin = IsAdmin
	param.UserLoginIsPlace = IsPlace
	param.ParentId = userId // 当前登录用户ID

	data := dao.NewUserDao().GetPlaceUserList(param)
	lists := data.Unwrap().([]*users.UserInfoWithPlace)
	for _, lst := range lists {
		userInfo := dao.NewUserDao().GetUserInfoById(lst.ParentId).Unwrap().(*users.UserModel)
		lst.ParentName = userInfo.UserName + "-" + userInfo.Name
		logic.NewUserLogic().FindPlaceChildrenList(lst.ID, lst)
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 新增商户用户
func HandleInsertPlaceUser(ctx *gin.Context) {
	param := &request.AdminUserInsertReq{}

	userId, _ := helper.GetUserIdFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	parentId, _ := helper.GetParentIdFromCtx(ctx)
	userName, _ := helper.GetUserNameFromCtx(ctx)

	if IsPlace == helper.TypeNumIsPlaceKa {
		param.KaUserId = userId
	}

	if IsAdmin == helper.TypeNumIsAdminStaff {
		param.KaUserId = parentId
	}

	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	id := dao.NewUserDao().InsertPlaceUser(param).Unwrap().(int)
	if id <= 0 {
		Response(ctx)("新增失败", CodeError, true)(OK)
		return
	}

	//添加修改用户分成日志
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.Change = 0
	upl.IsPlace = 1
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "新增商户用户"
	upl.UserId = id
	u := &users.UserModel{}
	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, u) // 添加订单操作日志
	Response(ctx)("新增成功", CodeSuccess, true)(OK)
}

// 修改商户用户
func HandleUpdatePlaceUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	//添加修改用户分成日志
	fmt.Println("当前信息：", param.ParentId)

	//查询该用户修改前的分成比例
	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)

	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserId = param.Id
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.IsPlace = 1
	upl.Change = int8(userInfo.ProfitProportion)
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "修改商户用户"

	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, userInfo) // 添加订单操作日志

	Response(ctx)("", CodeUpdateSuccess,
		dao.NewUserDao().UpdatePlaceUser(param).Unwrap())(OK)
}

func HandlePlaceUser(c *gin.Context) {
	userIdArr := dao.NewUserDao().QueryChildUserIds(127).Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	var Ids, placeId string
	for _, v := range placeIdArr {
		strId := strconv.Itoa(v) + ","

		placeId += strId
	}
	fmt.Println(placeId)
	var pricesIds []int
	global.Orm.Table("prices").Select("id").Where("place_id  in (?) and id in ( select id from prices where device_type_id = 12 GROUP BY create_at ) ", placeIdArr).Find(&pricesIds)

	for _, v := range pricesIds {
		strId := strconv.Itoa(v) + ","

		Ids += strId
	}
	fmt.Println(Ids)
	//查询所有分公司
	var param []struct {
		BranchIds int   `json:"branchIds"`
		PlacesIds []int `json:"placesIds"`
	}

	branchIds := dao.NewUserDao().GetPlaceBranchUserId().Unwrap().([]int)
	//查询分公司的所有网点
	for _, v := range branchIds {
		placesIdArr := dao.NewUserDao().GetPlacesId(v).Unwrap().([]int)
		placesStruct := struct {
			BranchIds int   `json:"branchIds"`
			PlacesIds []int `json:"placesIds"`
		}{}
		placesStruct.BranchIds = v
		placesStruct.PlacesIds = placesIdArr
		param = append(param, placesStruct)
	}
	//查询网点对应的商户
	for _, vla := range param {
		Ids := dao.NewUserDao().GetByPlaceIdBranchUserId(vla.BranchIds).Unwrap().([]int)
		if len(Ids) == 0 {
			continue
		}
		fmt.Println(Ids)
		usersModel := users.UserModel{}
		usersModel.BranchUserId = vla.BranchIds

		dao.NewUserDao().UpdateUserBranchUserId(Ids, &usersModel).Unwrap()
	}

	//修改商户的
	Response(c)("", CodeUpdateSuccess, param)(OK)
}
